package com.apexedu.biz.service.impl;

import com.apexedu.biz.Const;
import com.apexedu.biz.action.PortalAuthorizationAction;
import com.apexedu.biz.entity.TAccessAppReg;
import com.apexedu.framework.service.impl.AbstractBaseServiceSupport;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.Pager;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.identity.entity.TSysMenu;
import com.apexedu.identity.entity.TSysRole;
import com.apexedu.identity.entity.TSysRoleMenu;
import com.apexedu.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 门户授权查询
 * User: hc
 * Date: 14-5-15
 * Time: 下午2:35
 */
@Service("portalAuthorizationService")
public class PortalAuthorizationServiceImpl extends AbstractBaseServiceSupport {
    //点击新增资源时，不删除对应角色原有的门户权限，如果选择的权限已存在不做添加，否则添加  ,（未被使用）
    public void saveOrAdd(Object o) throws Exception {
        PortalAuthorizationAction action = (PortalAuthorizationAction) o;
        //从前台得到roleid
        String roleid = action.getParameter("rolesId");
        //从前台得到menuid
        String menuid = action.getParameter("menues");
        String[] roleids = roleid.split(",");
        String[] menuids = menuid.split(",");

        //用于存放新增的角色与资源的关系
        List<TSysRoleMenu> roleMenues = new ArrayList<TSysRoleMenu>();
        //roleids数组 roleids[0]为null

        for (int i = 1; i < roleids.length; i++) {
            //该角色下所有对应门户的资源
            String sql = "select * from t_sys_role_menu r , t_sys_menu m  where m.menuid=r.menuid and r.roleid=" + roleids[i] + " and m.belongtoapp=" + Const.PortalMenu;
            //查询出所有角色对应的资源
            List<TSysRoleMenu> list = DBUtil.queryAllBeanList(sql, TSysRoleMenu.class);
            if (!menuids[0].equals(Const.PortalMenu)) {   //不点击全选按钮时使用,资源编号前6为是000001
                for (int j = 0; j < menuids.length; j++) {
                    //判断是否存在 menuids[j]在list中是否存在，存在为1
                    int contains = 0;
                    if (list.size() > 0) {
                        for (int z = 0; z < list.size(); z++) {
                            if (list.get(z).getMenuid().equals(menuids[j]) && list.get(z).getRoleid().equals(roleids[i])) {
                                contains = 1;
                                break;
                            }
                        }
                        if (contains == 0) {
                            TSysRoleMenu roleMenu = new TSysRoleMenu();
                            roleMenu.setId(SeqFactory.getNewSequenceAlone());
                            roleMenu.setRoleid(roleids[i]);
                            roleMenu.setMenuid(menuids[j]);
                            roleMenues.add(roleMenu);
                        }
                    } else {
                        TSysRoleMenu roleMenu = new TSysRoleMenu();
                        roleMenu.setId(SeqFactory.getNewSequenceAlone());
                        roleMenu.setRoleid(roleids[i]);
                        roleMenu.setMenuid(menuids[j]);
                        roleMenues.add(roleMenu);
                    }
                }
            } else {   //点击全选按钮是使用
                for (int j = 1; j < menuids.length; j++) {
                    //判断是否存在 menuids[j]在list中是否存在，存在为1
                    int contains = 0;
                    if (list.size() > 0) {
                        for (int z = 0; z < list.size(); z++) {
                            if (list.get(z).getMenuid().equals(menuids[j]) && list.get(z).getRoleid().equals(roleids[i])) {
                                contains = 1;
                                break;
                            }
                        }
                        if (contains == 0) {
                            TSysRoleMenu roleMenu = new TSysRoleMenu();
                            roleMenu.setId(SeqFactory.getNewSequenceAlone());
                            roleMenu.setRoleid(roleids[i]);
                            roleMenu.setMenuid(menuids[j]);
                            roleMenues.add(roleMenu);
                        }
                    } else {
                        TSysRoleMenu roleMenu = new TSysRoleMenu();
                        roleMenu.setId(SeqFactory.getNewSequenceAlone());
                        roleMenu.setRoleid(roleids[i]);
                        roleMenu.setMenuid(menuids[j]);
                        roleMenues.add(roleMenu);
                    }

                }
            }
        }
        getBaseDao().saveAll(roleMenues);
    }

    @Override
    //点击修改资源时，删除对应角色原有的门户权限，保存新选择的门户权限
    public void saveOrUpdate(Object o) throws Exception {
        PortalAuthorizationAction action = (PortalAuthorizationAction) o;
        //从前台得到roleid
        String roleid = action.getParameter("rolesId");
        //从前台得到menuid
        String menuid = action.getParameter("menues");
        String[] roleids = roleid.split(",");
        String[] menuids = menuid.split(",");
        //用于存放新增的角色与资源的关系
        List<TSysRoleMenu> roleMenues = new ArrayList<TSysRoleMenu>();
        for (int i = 0; i < roleids.length; i++) {
            if (StringUtil.isNotBlank(roleids[i])) {
                String sql = "select * from t_sys_role_menu r , t_sys_menu m  where m.menuid=r.menuid and r.roleid=" + roleids[i] + " and m.belongtoapp=" + Const.PortalMenu;
                //查询出所有角色对应的资源
                List<TSysRoleMenu> list = DBUtil.queryAllBeanList(sql, TSysRoleMenu.class);
                if (!menuids[0].equals(Const.PortalMenu)) {   //不点击全选按钮时使用
                    for (int j = 0; j < menuids.length; j++) {
                        if (list.size() > 0) {
                            getBaseDao().deleteAll(list);
                        }
                        TSysRoleMenu roleMenu = new TSysRoleMenu();
                        roleMenu.setId(SeqFactory.getNewSequenceAlone());
                        roleMenu.setRoleid(roleids[i]);
                        roleMenu.setMenuid(menuids[j]);
                        roleMenues.add(roleMenu);
                    }
                } else {   //点击全选按钮是使用
                    for (int j = 1; j < menuids.length; j++) {
                        if (list.size() > 0) {
                            getBaseDao().deleteAll(list);
                        }
                        TSysRoleMenu roleMenu = new TSysRoleMenu();
                        roleMenu.setId(SeqFactory.getNewSequenceAlone());
                        roleMenu.setRoleid(roleids[i]);
                        roleMenu.setMenuid(menuids[j]);
                        roleMenues.add(roleMenu);
                    }
                }
            }
        }

        getBaseDao().saveAll(roleMenues);
    }

    @Override
    public void load(Object o) throws Exception {
        PortalAuthorizationAction action = (PortalAuthorizationAction) o;
        //获取角色id
        String roleid = action.getParameter("wid");
        String roleids = action.getParameter("roleid");
        String hql = "from TSysRole r where r.roleid = ?";
        if (StringUtil.isBlank(roleid) && StringUtil.isNotBlank(roleids)) {
            roleid = roleids;
        }
        //通过wid得到角色
        TSysRole tsysRole = getBaseDao().findFieldValue(hql, roleid);
        action.setTsysRole(tsysRole);
        //该角色下所有对应门户的资源
        String sql = "select * from t_sys_role_menu r , t_sys_menu m  where m.menuid=r.menuid and r.roleid=" + roleid + " and m.belongtoapp=" + Const.PortalMenu;

        //查询出所有角色对应的资源
        List<TSysRoleMenu> roleMenus = DBUtil.queryAllBeanList(sql, TSysRoleMenu.class);
        StringBuffer roleMenusBuffer = new StringBuffer();
        for (int i = 0; i < roleMenus.size(); i++) {
            roleMenusBuffer.append(roleMenus.get(i).getMenuid());
            if (i < roleMenus.size() - 1) {
                roleMenusBuffer.append(",");
            }
        }
        action.setParameter("roleid", roleid);
        action.setParameter("roleMenusBuffer", roleMenusBuffer);
        List<TSysMenu> list = queryPortalMenu();
        action.setParameter("menulist", list);
        action.setParameter("portalname", "门户资源");
    }

    @Override
    /**
     * 展示tab页业务系统
     */
    public List<TSysRole> list(Object o, Pager pager) throws Exception {
        PortalAuthorizationAction action = (PortalAuthorizationAction) o;
        //表示新增还是修改
        String flag = action.getParameter("flag");
        //得到系统编号
        String appid = action.getParameter("appid");
        //得到存在的角色
        String roleids = action.getParameter("rolesId");

        if (StringUtil.isNotBlank(flag)) {
            if (flag.equals("save")) {
//                this.saveOrAdd(o);
        } else if (flag.equals("update")) {
            this.saveOrUpdate(o);
            action.setMsg("保存成功！");
        }
        }
        List<TAccessAppReg> list = queryAllMenu();
        if (StringUtil.isNotBlank(appid)) {
            int appno = 0;
            //根据appid得到对应的下标
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getAppid().equals(appid)) {
                    appno = i;
                    break;
                }
            }
            action.setAppno(appno);
        }
        //查询出所有业务系统中所有拥有门户资源的角色
        String sql = "select r.roleid from t_sys_menu m,t_sys_role_menu r where m.menuid=r.menuid and m.belongtoapp=" + Const.PortalMenu + "group by r.roleid";
        List<TSysRoleMenu> sysRoleMenus = DBUtil.queryAllBeanList(sql, TSysRoleMenu.class);
        StringBuffer roles = new StringBuffer();
        //角色id拼装成字符串
        for (int i = 0; i < sysRoleMenus.size(); i++) {
            roles.append(",");
            roles.append(sysRoleMenus.get(i).getRoleid());
        }
        action.setParameter("appid", appid);
        action.setParameter("roles", roles);
        action.setParameter("rolesId", roleids);
        //业务系统列表
        action.setListApp(list);
        return null;
    }

    @Override
    public boolean remove(Object o) throws Exception {
       //PortalAuthorizationAction action = (PortalAuthorizationAction) o;
//        String wid = action.getWid();
//        boolean msg = false;
//        if (StringUtil.isNotBlank(wid)) {
//            String[] menu = wid.split(",");
//            if (null != menu && menu.length > 0) {
//                for (String id : menu) {
//                    DBUtil.executeSQL("update t_sys_menu t set t.sftjdmh ='' where t.menuid= ?  ", id);
//                }
//            }
//        }
        return false;
    }


    /**
     * 查询所有的系统名称
     *
     * @return List<TAccessAppReg>
     */
    public List<TAccessAppReg> queryAllMenu() {
        String sql = "select appid ,appname from T_ACCESS_APP_REG where state=1 order by ordernum desc,appid";
        List<TAccessAppReg> list = DBUtil.queryAllBeanList(sql, TAccessAppReg.class);
        return list;
    }

    /**
     * 查询所有业务系统下对应的角色
     */
    public List<TSysRole> queryAllRole(String appid, String appno) {
        List<TAccessAppReg> appRegs = queryAllMenu();
        if (StringUtil.isBlank(appid) && StringUtil.isBlank(appno)) {
            try {
                appid = appRegs.get(0).getAppid();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (StringUtil.isNotBlank(appno)) {
            appid = appRegs.get(Integer.parseInt(appno)).getAppid();
        }
        String sql = "select roleid,rolename from T_SYS_ROLE where belongtoapp =?";
        List<TSysRole> list = DBUtil.queryAllBeanList(sql, TSysRole.class, appid);

        return list;

    }

    /**
     * 查询所有属于门户的资源
     */
    public List<TSysMenu> queryPortalMenu() {
        String sql = "select m.*,x.zdmc as ywxtmc from T_SYS_MENU m " +
                "inner join (select c.zdbm,c.zdmc from T_SYS_CODE c where  c.zdlb='zylx') x on  x.zdbm= m.srctype " +
                "where belongtoapp =? order by menuid";
        List<TSysMenu> list = DBUtil.queryAllBeanList(sql, TSysMenu.class, Const.PortalMenu);
        return list;
    }

    //点击角色保存资源
    public String saveRoleMenu(String roleid, String menus) {
        String[] menuslist = menus.split(",");
        //该角色下所有对应门户的资源
        String sql = "select * from t_sys_role_menu r , t_sys_menu m  where m.menuid=r.menuid and r.roleid=" + roleid + " and m.belongtoapp=" + Const.PortalMenu;
        List<TSysRoleMenu> list = DBUtil.queryAllBeanList(sql, TSysRoleMenu.class);
        //用于存放新增的角色与资源的关系
        List<TSysRoleMenu> roleMenues = new ArrayList<TSysRoleMenu>();
        if (menuslist[0].equals(roleid)) { //点击全选时
            for (int i = 1; i < menuslist.length; i++) {
                if (list.size() > 0) {
                    getBaseDao().deleteAll(list);
                }
                if (!menuslist[i].equals("")) {
                    TSysRoleMenu roleMenu = new TSysRoleMenu();
                    roleMenu.setId(SeqFactory.getNewSequenceAlone());
                    roleMenu.setRoleid(roleid);
                    roleMenu.setMenuid(menuslist[i]);
                    roleMenues.add(roleMenu);
                }
            }
        } else {
            for (int i = 0; i < menuslist.length; i++) {
                if (list.size() > 0) {
                    getBaseDao().deleteAll(list);
                }
                if (!menuslist[i].equals("")) {
                    TSysRoleMenu roleMenu = new TSysRoleMenu();
                    roleMenu.setId(SeqFactory.getNewSequenceAlone());
                    roleMenu.setRoleid(roleid);
                    roleMenu.setMenuid(menuslist[i]);
                    roleMenues.add(roleMenu);
                }
            }
        }
        if (roleMenues.size() > 0) {
            getBaseDao().saveAll(roleMenues);
        }
        //保存成功
        return Const.MESSAGE_SAVE_SUCCESS;
    }
}
